﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using UnityEngine;
using System.IO;
using System.Security.Cryptography;

namespace DashFire {
  public class ResLoadHelper {
    private static string s_StreamingAssetsPath = string.Empty;
    private static string s_ResServerURLAbs = string.Empty;
    private static string s_BuildInURLAbs = string.Empty;
    private static string s_CachedURLAbs = string.Empty;

    #region File Path
    public static string GetFilePath(ResPathType pathType, string resName) {
      switch (pathType) {
        case ResPathType.Buildin: {
            return GetBuildInURLAbs() + resName;
          }
        case ResPathType.Cache: {
            return GetCachedURLAbs() + resName;
          }
        case ResPathType.Remote: {
            return GetRemoteUrlForResAbs() + resName;
          }
      }
      return string.Empty;
    }
    private static string GetRemoteUrlForResAbs() {
      if (!string.IsNullOrEmpty(s_ResServerURLAbs)) {
        return s_ResServerURLAbs;
      } else {
        s_ResServerURLAbs = string.Format("{0}/{1}/{2}_res/",
          ResUpdateControler.s_ClientVersionInfo.ResServerURL,
          ResUpdateControler.s_ClientVersionInfo.GroupName,
          ResUpdateControler.s_ClientVersionInfo.Platform);
        return s_ResServerURLAbs;
      }
    }
    public static string GetStreamingAssetPath() {
      if (!string.IsNullOrEmpty(s_StreamingAssetsPath)) {
        return s_StreamingAssetsPath;
      } else {
        StringBuilder sb = new StringBuilder();
#if UNITY_ANDROID && !UNITY_EDITOR
      sb.Append("jar:file://");
      sb.Append(Application.dataPath);
      sb.Append("!/assets/");
#else
        sb.Append("file://");
        sb.Append(Application.streamingAssetsPath);
        sb.Append("/");
#endif
        s_StreamingAssetsPath = sb.ToString();
        return s_StreamingAssetsPath;
      }
    }
    public static string GetBuildInURLAbs() {
      if (!string.IsNullOrEmpty(s_BuildInURLAbs)) {
        return s_BuildInURLAbs;
      } else {
        StringBuilder sb = new StringBuilder();
        sb.Append(GetStreamingAssetPath());
        sb.Append(ResUpdateConfig.s_ResBuildInPath);
        s_BuildInURLAbs = sb.ToString();
        return s_BuildInURLAbs;
      }
    }
    public static string GetCachedURLAbs() {
      if (!string.IsNullOrEmpty(s_CachedURLAbs)) {
        return s_CachedURLAbs;
      } else {
        StringBuilder sb = new StringBuilder();
        sb.Append(Application.persistentDataPath);
        sb.Append("/");
        sb.Append(ResUpdateConfig.s_ResCachePath);
        s_CachedURLAbs = sb.ToString();
        return s_CachedURLAbs;
      }
    }
    #endregion

    #region Res Check
    public static bool IsResConfigCached(ResFileType fileType) {
      switch (fileType) {
        case ResFileType.ResVersion: {
            return ResUpdateControler.s_ClientVersionInfo.IsResVersionConfigCached;
          }
        case ResFileType.ResInner: {
            return ResUpdateControler.s_ClientVersionInfo.IsResInnerConfigCached;
          }
      }
      return false;
    }
    public static bool IsResAssetCached(string resShortName) {
      ClientResVersionData lrv = ClientResVersionProvider.Instance.GetDataByAssetShortName(resShortName);
      if (lrv == null) {
        return false;
      }
      string resCachedUrl = GetCachedURLAbs() + lrv.m_AssetBundleName;
      if (!File.Exists(resCachedUrl)) {
        return false;
      }
      return true;
    }
	public static bool IsResNeedUpdate(string abName, string md5)
    {
      ClientResVersionData lrv = ClientResVersionProvider.Instance.GetDataByAssetBundleName(abName);
      if (lrv == null) {
        return true;
      }
      if (string.Compare(md5, lrv.m_MD5, true) != 0) {
        return true;
      }
      string resCachedUrl = GetCachedURLAbs() + abName;
      if (!File.Exists(resCachedUrl)) {
        return true;
      }
      return false;
    }
    public static bool IsResAssetbundleCached(string abName)
    {
      ClientResVersionData lrv = ClientResVersionProvider.Instance.GetDataByAssetBundleName(abName);
      if (lrv == null) {
        return false;
      }
      string resCachedUrl = GetCachedURLAbs() + lrv.m_AssetBundleName;
      if (!File.Exists(resCachedUrl)) {
        return false;
      }
      return true;
    }
    public static ClientResVersionData GetResVersionDataByAssetName(string resName) {
      ClientResVersionData resVersionData = ClientResVersionProvider.Instance.GetDataByAssetShortName(resName);
      if (resVersionData == null) {
        ResLoadHelper.Log("GetResVersionDataByAssetId GetResVersionData failed resName:" + resName);
        return null;
      }
      return resVersionData;
    }
    #endregion

    #region Tools
    public static long CaculateABSize(List<string> toUpgradeRes)
    {
      long size = 0;
      for (int i = 0; i < toUpgradeRes.Count; i++) {
        ResVersionData data = ResVersionProvider.Instance.GetDataByAssetBundleName(toUpgradeRes[i]);
        if (data != null) {
          size += data.m_Size;
        }
      }
      return size;
    }
    public static void Log(string msg)
    {
      LogicForGfxThread.LogicLog("{0}", msg);
      //UnityEngine.Debug.Log(msg);
    }
    public static void ErrLog(string msg)
    {
      LogicForGfxThread.LogicErrorLog("{0}", msg);
      //UnityEngine.Debug.LogError(msg);
    }
    public static string GetDynamicUrl(string url)
    {
      url += "?time=" + DateTime.Now.ToString("yyyyMMddhhmmss");
      return url;
    }
    public static string FormatSheetZipFile(string version)
    {
      return string.Format("sheet{0}.ab", version);
    }
    public static string Combine(string path1, string path2)
    {
      string retPath = string.Empty;
      path1 = ConvertPathSlash(path1);
      path2 = ConvertPathSlash(path2);
      if (path1.EndsWith("/") && path2.StartsWith("/")) {
        retPath = path1 + path2.Substring(1);
      } else if (!path1.EndsWith("/") && !path2.StartsWith("/")) {
        retPath = path1 + "/" + path2;
      } else {
        retPath = path1 + path2;
      }
      return retPath;
    }
    public static string ConvertPathSlash(string filePath)
    {
      return filePath.Replace("\\", "/");
    }
    #endregion
  }
}
